# -*- coding: UTF-8 -*-
import asyncio
from typing import Dict

from celery import Task

from common_libs.rpc_utils import send_request
from dispatcher.celery_work.celery_app import celery_instance
from dispatcher.common_utils.clutter_utils import update_task_cache, get_task_await_seconds
from dispatcher.common_utils.constants import logger


class DispatchTask(Task):
    def __init__(self):
        pass

    def on_success(self, retval, task_id, args, kwargs):
        logger.info(f'--on_success--,task_id:{task_id},args:{args},kwargs:{kwargs}')
        data_block = kwargs.get("data_block")
        data_block["state"] = "success"
        asyncio.run(update_task_cache(data_block))
        pass

    def on_failure(self, exc, task_id, args, kwargs, einfo):
        logger.info(f'--on_failure--,task_id:{task_id},args:{args},kwargs:{kwargs},einfo:{einfo}')
        data_block = kwargs.get("data_block")
        data_block["state"] = "fail"
        asyncio.run(update_task_cache(data_block))
        pass

    def before_start(self, task_id, args, kwargs):
        pass

    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        pass


@celery_instance.task(base=DispatchTask, bind=True, name="handle.handle_tasks.handle_dispatch_task")
def handle_dispatch_task(self, data_block: Dict):
    url = data_block.get("url")
    method = data_block.get("method")
    body = data_block.get("body")
    param = data_block.get("param")
    try:
        asyncio.run(send_request(method=method, url=url, params=param, body=body))
    except Exception as exc:
        data_block["state"] = "retry"
        asyncio.run(update_task_cache(data_block))
        count_down = get_task_await_seconds(data_block.get("retry_time_interval"))
        max_retries = data_block.get("max_try_times")
        self.on_retry(exc=exc, count_down=count_down, max_retries=max_retries)

